extends IDragController


class_name InventoryDragController
"""
道具拖拽控制
"""


## 对于堆叠的物品拖拽数目
@export var drag_split_count: int = 0


func drag(drag_from: Control) -> Variant:
    var item: InventoryItem = null
    if drag_from is InventorySlot:
        var slot: InventorySlot = drag_from as InventorySlot
        if not slot.is_empty():
            # 全部拖拽
            if drag_split_count < 1 or slot.inventory_item.amount <= drag_split_count:
                item = slot.inventory_item
                slot.set_item(null)
            else:
                item = slot.inventory_item.clip(drag_split_count)
    return item

func get_drag_preview(drag_from: Control, data: Variant) -> Control:
    var item: InventoryItem = data as InventoryItem
    var slot: InventorySlot = drag_from as InventorySlot
    var drag_ui: Control = slot.duplicate() as Control
    drag_ui.mouse_filter = Control.MOUSE_FILTER_IGNORE
    drag_ui.global_position = drag_from.get_global_mouse_position()
    NodeHelper.add_child(self, drag_ui)
    drag_ui.set_item(item)
    return drag_ui

func can_drop(drag_to: Control, data: Variant) -> bool:
    # 相同合并,不同则交换位置
    return drag_to is InventorySlot

func cancel_drop(drag_from: Control, data: Variant) -> void:
    var slot: InventorySlot = drag_from as InventorySlot
    var item: InventoryItem = data as InventoryItem
    if slot.is_empty():
        slot.set_item(item)
    else:
        slot.inventory_item.amount += item.amount

func drop(drag_from: Control, drag_to: Control, data: Variant) -> void:
    var slot_from: InventorySlot = drag_from as InventorySlot
    var slot_to: InventorySlot = drag_to as InventorySlot
    var item: InventoryItem = data as InventoryItem
    # 空的位置直接放置
    if slot_to.is_empty():
        slot_to.set_item(item)
        return
    var remote_item: InventoryItem = slot_to.inventory_item
    # 不一样的道具或剩余容量不够则进行位置交换
    if not slot_to.is_equal(item) or not slot_to.is_space(item.amount):
        # 拖拽后剩余的数量合并后一起交换
        if not slot_from.is_empty():
            item.amount += slot_from.inventory_item.amount
        slot_from.set_item(remote_item)
        slot_to.set_item(item)
        return
    # 相同项进行数量合并
    remote_item.amount += item.amount

func drop_to_floor(drag_from: Control, data: Variant) -> void:
    cancel_drop(drag_from, data)
